package org.example;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 通过 ObjectOutputStream 和  ObjectInputStream在服务端和客户端之间发送 "对象"
 * 多次重复发送, 在读取的时候不用判断结束条件.直接读对象.
 * <p>
 * 注意:客户端的 objectOutputStream和服务端中的 objectInputStream,两者必须保持一致
 * 两者可以都在循环中 (每次都 new一个)
 * 两者也可以都在循环外 (总共new一个)
 * <p>
 * 不可以一个在循环体外,一个在循环体内.会报错.
 * <p>
 * 如果客户端 objectOutputStream在循环内,服务端objectInputStream在循环外,报错
 * java.io.StreamCorruptedException: invalid type code: AC
 * <p>
 * 如果客户端objectOutputStream在循环外,服务端objectInputStream在循环内,报错
 * java.io.StreamCorruptedException: invalid stream header: 71007E00
 */
public class ServerObject {

    //    static Person sendObj = new Person("严金玉");
    static String sendObj = "我是服务端,1234Abc";

    public static void main(String[] args) throws Exception {

        ServerSocket serverSocket = new ServerSocket(30000);
        System.out.println("-------------server is ready!!!-------------");

        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println(socket);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    Object o = null;

                    try {
                        InputStream inputStream = socket.getInputStream();
                        OutputStream outputStream = socket.getOutputStream();

                        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
                        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);

                        while (true) {
                            o = objectInputStream.readObject();
                            System.out.println("server receive:" + o);
                            System.out.println("获取到对象的类型:" + o.getClass());

                            objectOutputStream.writeObject(sendObj);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }
    }
}
